package com.zkdcloud.controller;

import com.xdja.interceptor.annotation.BeforeProcess;
import com.xdja.interceptor.annotation.Validate;
import com.xdja.interceptor.bean.ResultBean;
import com.xdja.interceptor.exception.InvokeException;
import com.xdja.interceptor.util.ValidateUtils;
import com.zkdcloud.aspectInterceptor.validatie.LoginControllerValidate;
import com.zkdcloud.domain.Admin;
import com.zkdcloud.service.AdminService;
import com.zkdcloud.util.TokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import static com.zkdcloud.constant.Constants.HTTP_CONSTANTS.HTTP_SUCCESS;
import static com.zkdcloud.constant.Constants.HTTP_CONSTANTS.OPERATOR_SUCCESS;

/**
 * 登录接口
 *
 * @author zk123
 * @version 2018/4/29
 */
@RestController
@RequestMapping(value = "/mg/")
public class LoginController {
    private static Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private AdminService adminService;

    /**
     * 注册admin
     *
     * @param admin admin
     */
    @BeforeProcess(validate = {
            @Validate(value = LoginControllerValidate.class,method = "validateAdminUAP"),
            @Validate(value = LoginControllerValidate.class,method = "checkSameUserName")
    })
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public ResultBean registerAdmin(Admin admin){
        adminService.addAdminWithEncPwd(admin);
        return ResultBean.successResult(OPERATOR_SUCCESS);
    }

    /**
     * admin 登录
     *
     * @param admin admin
     * @return resultBean
     */
    @BeforeProcess(validate = @Validate(value = LoginControllerValidate.class,method = "validateAdminUAP"))
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public ResultBean loginAdmin(Admin admin) throws InvokeException {
        Admin loginAdmin = adminService.checkLogin(admin.getUserName(),admin.getPassword());

        if(loginAdmin == null){
            return ResultBean.failResult("账号或密码错误");
        }
        return ResultBean.successResult(HTTP_SUCCESS,TokenUtil.makeAdminToken(loginAdmin));
    }

    @RequestMapping(value = "test",method = RequestMethod.GET)
    public ResultBean test(){
        return ResultBean.successResult("连接成功");
    }
}
